package linkedlist.test25;

import listbyorder.utils.ListNode;

/**
 * K 个一组翻转链表
 *
 * @author code_yc
 * @version 1.0
 * @date 2020/7/14 13:48
 */
public class Solution1 {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || head.next == null) return head;
        if (k == 1) return head;
        // 首先将前k个元素进行反转
        int n = k - 1;
        ListNode t = head;
        while (n != 0 && t.next != null) {
            t = t.next;
            n--;
        }
        if (n != 0) return head;
        ListNode nextL = t.next;
        t.next = null;
        // 反转当前的head
        ListNode newH = reverse(head);
        head.next = reverseKGroup(nextL, k);
        return newH;
    }

    private ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode next;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}
